package com.feiwo.nonego.rpc.serialization.protostuff;

import com.feiwo.nonego.rpc.serialization.api.Serialization;
import com.feiwo.nonego.rpc.serialization.api.exception.SerializerException;
import com.feiwo.nonego.rpc.spi.annotation.SPIClass;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 *
 * @author feiwo 2025-08-14
 */
@SPIClass
public class ProtostuffSerialization implements Serialization {

    private final Map<Class<?>, Schema<?>> cacheSchema = new ConcurrentHashMap<>();

    private final Objenesis objenesis = new ObjenesisStd(true);

    @SuppressWarnings("unchecked")
    @Override
    public <T> byte[] serialize(T obj) {
        if (Objects.isNull(obj)) {
            throw new SerializerException("serialization object is null");
        }

        var buffer = LinkedBuffer.allocate(io.protostuff.LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema<T> schema = (Schema<T>) getSchema(obj.getClass());
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new SerializerException(e.getMessage(),e);
        }finally {
            buffer.clear();
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        if (Objects.isNull(data)) {
            throw new SerializerException("deserialize data is null");
        }

        try {
            var obj = objenesis.newInstance(clazz);
            var schema = getSchema(clazz);
            ProtostuffIOUtil.mergeFrom(data, obj, schema);
            return obj;
        } catch (Exception e) {
            throw new SerializerException(e.getMessage(), e);
        }
    }

    private <T> Schema<T> getSchema(Class<T> clazz) {
        var schema = cacheSchema.get(clazz);
        if (Objects.isNull(schema)) {
            schema = RuntimeSchema.createFrom(clazz);
            if (Objects.nonNull(schema)) {
                cacheSchema.put(clazz, schema);
            }
        }
        //noinspection ReassignedVariable,unchecked
        return (Schema<T>) schema;
    }
}
